package com.bjsxt.controller.system;

import com.bjsxt.constants.Constants;
import com.bjsxt.domain.Menu;
import com.bjsxt.dto.MenuDto;
import com.bjsxt.service.MenuService;
import com.bjsxt.utils.ShiroSecurityUtils;
import com.bjsxt.vo.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜单控制器
 */
@RestController
@RequestMapping("system/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    /**
     * 查询所有菜单和权限
     *
     * @return
     */
    @GetMapping("listAllMenus")
    public AjaxResult listAllMenus(MenuDto menuDto) {
        List<Menu> menus = this.menuService.listAllMenus(menuDto);
        return AjaxResult.success(menus);
    }

    /**
     * 查询菜单的下拉树【只查询可用的菜单】
     *
     * @return
     */
    @GetMapping("selectMenuTree")
    public AjaxResult selectMenuTree() {
        MenuDto menuDto = new MenuDto();
        menuDto.setStatus(Constants.STATUS_TRUE);
        return AjaxResult.success(this.menuService.listAllMenus(menuDto));
    }

    /**
     * 添加菜单
     *
     * @param menuDto
     * @return
     */
    @PostMapping("addMenu")
    public AjaxResult addMenu(@Validated MenuDto menuDto) {
        menuDto.setSimpleUser(ShiroSecurityUtils.getCurrentSimpleUser());
        return AjaxResult.toAjax(this.menuService.addMenu(menuDto));
    }

    /**
     * 修改菜单
     *
     * @param menuDto
     * @return
     */
    @PutMapping("updateMenu")
    public AjaxResult updateMenu(@Validated MenuDto menuDto) {
        menuDto.setSimpleUser(ShiroSecurityUtils.getCurrentSimpleUser());
        return AjaxResult.toAjax(this.menuService.updateMenu(menuDto));
    }

    /**
     * 根据id查询一个菜单
     *
     * @param menuId
     * @return
     */
    @GetMapping("getMenuById/{menuId}")
    public AjaxResult getMenuById(@PathVariable Long menuId) {
        Menu menu = this.menuService.getOne(menuId);
        return AjaxResult.success(menu);
    }

    /**
     * 根据id删除菜单【删除菜单之前需要判断是否有子节点，如果有子节点则删除失败】
     *
     * @param menuId
     * @return
     */
    @DeleteMapping("deleteMenuById/{menuId}")
    public AjaxResult deleteMenuById(@PathVariable Long menuId) {
        if (this.menuService.hasChildByMenuId(menuId)) {
            return AjaxResult.fail("删除失败，当前删除的菜单有子节点，请先删除子节点");
        }
        return AjaxResult.success(this.menuService.deleteMenuById(menuId));
    }

    /**
     * 根据角色id查询菜单权限id数据
     *
     * @param roleId
     * @return
     */
    @GetMapping("getMenuIdsByRoleId/{roleId}")
    public AjaxResult getMenuIdsByRoleId(@PathVariable Long roleId) {
        List<Long> ids = this.menuService.getMenusIdsByRoleId(roleId);
        return AjaxResult.success(ids);
    }
}
